import React, {useEffect, useMemo, useState} from 'react';
import {
  Image,
  SafeAreaView,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from 'react-native';
import CommonFlatList, {RefreshState} from '../components/CommonFlatList';
import {getMovieListApi} from '../api/movieApi';
import Like from '../assets/icons/Like';
import Clock from '../assets/icons/Clock';
import dayjs from 'dayjs';
import {DEVICE_WIDTH} from '../utils/screen';

let page = 0;

/**
 * 获取首页专题背景色
 * @param index 专题id
 * @return 背景色
 */
const getChapterBgColor = index => {
  const indexStr = index.toString();
  const id = indexStr.substr(indexStr.length - 1);
  const colors = [
    '#79CDCD',
    '#71C671',
    '#4169E1',
    '#3CB371',
    '#EE82EE',
    '#F4A460',
    '#FF7256',
    '#5F9EA0',
    '#79CDCD',
    '#BC8F8F',
  ];
  return colors[id];
};

const renderItemRight = (e: any) => {
  if (e.envelopePic) {
    return (
      <Image
        style={styles.img}
        source={{
          uri: e.envelopePic,
        }}
        resizeMode={'cover'}
      />
    );
  } else {
    return (
      <View
        style={[styles.tag, {backgroundColor: getChapterBgColor(e.chapterId)}]}>
        <Text style={styles.chapterName} numberOfLines={1}>
          {e.superChapterName}
        </Text>
      </View>
    );
  }
};

const renderItem = ({item}) => {
  return (
    <TouchableOpacity
      activeOpacity={0.8}
      style={styles.item}
      onPress={() => {}}>
      <View style={styles.leftWrap}>
        <Text style={styles.title} numberOfLines={2}>
          {item.title}
        </Text>
        <Text style={styles.desc} numberOfLines={3}>
          {item.desc}
        </Text>
        <View style={styles.leftBottomWrap}>
          <Like
            style={styles.icon}
            size={26}
            color={item.collect ? '#ec705a' : '#d8d7d9'}
          />
          <Clock style={styles.icon} size={26} color={'#d8d7d9'} />
          <Text style={styles.time}>
            {dayjs(item.publishTime).format('YYYY-MM-DD')}
          </Text>
          <Text style={styles.author}>{item.author}</Text>
        </View>
      </View>
      {renderItemRight(item)}
    </TouchableOpacity>
  );
};

const List = () => {
  const [listData, setListData] = useState([]);
  const [refreshState, setRefreshState] = useState(RefreshState.Idle);

  // 设置listData 记忆缓存，防止state变化导致重新渲染页面
  const memoList = useMemo(() => {
    return listData;
  }, [listData]);

  const onHeaderRefresh = () => {
    setRefreshState(RefreshState.HeaderRefreshing);

    // 模拟网络请求
    setTimeout(async () => {
      // 模拟网络加载失败的情况
      if (Math.random() < 0.2) {
        setRefreshState(RefreshState.Failure);
        return;
      }

      //获取测试数据
      let dataList = await getArticleList(true);
      setListData(dataList);
      setRefreshState(
        dataList.length < 1 ? RefreshState.EmptyData : RefreshState.Idle,
      );
    }, 2000);
  };

  // 获取测试数据
  const getArticleList = async isRefresh => {
    if (isRefresh) {
      page = 0;
    }
    const {data, errorCode} = await getMovieListApi(page);
    if (errorCode === 0) {
      //todo:需要增加判断返回数量是否==pageSize来判断是否有下一页
      page++;
      if (isRefresh) {
        return [...data.datas];
      } else {
        return [...listData, ...data.datas];
      }
    }
  };

  const onFooterRefresh = () => {
    setRefreshState(RefreshState.FooterRefreshing);

    // 模拟网络请求
    setTimeout(async () => {
      // 模拟网络加载失败的情况
      if (Math.random() < 0.2) {
        setRefreshState(RefreshState.Failure);
        return;
      }

      // 获取测试数据
      let dataList = await getArticleList(false);
      setListData(dataList);
      setRefreshState(
        //todo: demo模仿默认数据超过80就没有更多数据
        dataList.length > 80 ? RefreshState.NoMoreData : RefreshState.Idle,
      );
    }, 2000);
  };

  useEffect(() => {
    getArticleList(true).then(r => setListData(r));
  }, []);

  return (
    <SafeAreaView style={styles.container}>
      <CommonFlatList
        data={memoList}
        keyExtractor={item => item.id}
        renderItem={renderItem}
        refreshState={refreshState}
        onHeaderRefresh={onHeaderRefresh}
        onFooterRefresh={onFooterRefresh}
      />
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#EFEFEF',
  },
  item: {
    width: DEVICE_WIDTH - 20,
    marginTop: 10,
    marginHorizontal: 10,
    padding: 16,
    borderRadius: 8,
    flexDirection: 'row',
    backgroundColor: '#fff',
  },
  leftWrap: {
    flexDirection: 'column',
    flex: 1,
    marginRight: 10,
  },
  leftBottomWrap: {
    marginTop: 10,
    flexDirection: 'row',
    alignItems: 'center',
    height: 30,
  },
  title: {
    color: '#333333',
    fontSize: 16,
    fontWeight: 'bold',
  },
  desc: {
    marginTop: 8,
    color: '#999999',
    fontSize: 14,
  },
  img: {
    width: 80,
    height: 80,
  },

  tag: {
    width: 80,
    height: 80,
    borderRadius: 40,
    justifyContent: 'center',
    alignItems: 'center',
  },
  chapterName: {
    color: '#fff',
    fontSize: 15,
    fontWeight: '500',
  },
  icon: {
    marginRight: 6,
  },
  time: {
    color: '#939293',
    fontSize: 14,
    marginRight: 6,
  },
  author: {
    color: '#a8a6a8',
    fontSize: 13,
  },
});

export default List;
